<?php

namespace app\index\controller;
use think\Controller;
use app\admin\model\Foregroundmenu;

class IndexBase extends Controller{
    //用户信息变量配置
    protected $_userCfg;
    //请求方式 get|post
    protected $method;
    //是否是ajax请求 true|false
    protected $isAjax;
    //页面标题
    protected $title;

    protected $param = [];
    public $com_id = 0;

    protected function _initialize()
    {
        //检查登录
        $this->checkLoginStatus();
        //检查请求方式
        $this->checkRequestMethod();
        //检查页面配置信息
        $this->checkPageConf();
        //获取页面导航标签
        $this->getPageTags();

        $this->initParams();
    }

    /*
     * 初始化参数
     */
    protected function initParams(){
        $curr_day = date('j');
        if($curr_day>10){
            $this->param['default_month'] = date('Y-m-d');
        }else{
            $this->param['default_month'] = date('Y-m-d', strtotime('-1 month'));
        }
    }

    protected function getSysParam($key, $val='', $format='Y-m'){
        if($val!=''){
            cookie($key,$val);
            return date($format, strtotime($val));
        }
        $value = cookie($key);
        if(empty(cookie($key))){
            $value = $this->param[$key];
            cookie($key,$value);
        }
        return date($format, strtotime($value));
    }

    /**
     * 获取页面导航标签
     * @author carl.zhou
     * @return array
     */
    protected function getPageTags(){
        $request_url = strtolower($this->request->url());
        $path = strtolower($this->request->path());
        $path = $this->getPurePath($path);

        $tagList = cookie('tagList');
        if (empty($tagList)) {
            $tagList = [];
        }

        //写入标签列表
        if ($this->method === 'get' && $this->isAjax === false) {
            $tagList[$path] = [
                'title' => $this->title,
                'url' => $request_url,
            ];

            while (count($tagList)>6) {
                array_shift($tagList);
            }
            cookie('tagList', $tagList);
        }
        $tagList = array_reverse($tagList);
        $this->assign('_tagList', $tagList);
        $this->assign('_currPath', $path);
    }

    /**
     * 获取最简链接
     * @author carl.zhou 2017-08-25
     * @param $path
     * @return mixed|string
     */
    protected function getPurePath($path){
        $path = preg_replace('/\..*?$/', '', $path);
        $temp = explode('/', $path);
        do{
            $act = strtolower(array_pop($temp));
            if ($act !== 'index' && $act!=='') {
                array_push($temp, $act);
                break;
            }
        }
        while (count($temp)>0);
        $path = implode('/', $temp);
        if ($path=='') {
            $path = '/';
        }
        return $path;
    }


    /*
    /**
     * 检查页面配置信息
     * @author carl.zhou
     */
    protected function checkPageConf(){
        $this->com_id = session('com_id');
        $role = session('user_number');
        $database = config('database');
        $auth = $database['auth'];

        $controller = strtolower($this->request->controller());
        $action = strtolower($this->request->action());
        if (!is_array($auth)) {
            $auth = [];
        }

        if (!$this->checkRole($auth, $controller, $action, $role)) {
            $this->error('您没有权限', '/index');
        }

        //获取左侧菜单
        //$sidebar = config('sidebar');
        $sidebar = $this->sidebars($this->com_id);


        //$auth菜单与权限 $role操作人 $sidebar菜单
        $roleMenu = $this->getRoleMenu($auth, $role, $sidebar);
        $this->assign('roleMenu', $roleMenu);

        $this->getActiveMenuId($sidebar, $controller, $action);

        $pageInfo = config('pageInfo');
        $title = $this->getPageTitle($pageInfo, $controller, $action);
        $this->title = empty($title) ? '未定义' : $title;
        $this->assign('title', $this->title);
    }

    //左侧菜单
    protected function sidebars(){
        $foregroundmenu = new Foregroundmenu;
        $_opt  = ['pid'=>0,'status'=>1,'com_id'=>$this->com_id];
        $menus = $foregroundmenu->getMenu($_opt);
        $menu_array = array();
        foreach($menus as $menu){
            $menu_array[$menu['method']] =array(
                                                'id'=>$menu['element_id'],
                                                'url'=>$menu['url'],
                                                'icon'=>$menu['icon'],
                                                'title'=>$menu['title'],
                                                );
            $_opt  = ['pid'=>$menu['menu_id']];
            $lists = $foregroundmenu->getMenu($_opt);
            $menu_list = array();
            foreach ($lists as $list){
                $menu_list[$list['method']] = array(
                                                    'id'=>$list['element_id'],
                                                    'url'=>$list['url'],
                                                    'icon'=>$list['icon'],
                                                    'title'=>$list['title'],
                                                    );
            }
            if(count($menu_list)>0){
                $menu_array[$menu['method']]['list']= $menu_list;
            }
        }
        return $menu_array;
    }


    /*
     * 获取当前菜单id
     */
    protected function getActiveMenuId($sidebar, $controller, $action){
        $key = $controller.'-'.$action;
        if(array_key_exists($key, $sidebar)){
            $item = $sidebar[$key];
            $top_option_id = $item['id'];
            $this->assign('top_option_id', $top_option_id);
        }elseif(array_key_exists($controller, $sidebar)){
            $item = $sidebar[$controller];
            $top_option_id = $item['id'];
            $this->assign('top_option_id', $top_option_id);
        }
        if(isset($item['list']) && array_key_exists($action, $item['list'])){
            $sec_option_id = $item['list'][$action]['id'];
            $this->assign('sec_option_id', $sec_option_id);
        }
    }
    /*
     * 根据权限获取左侧菜单
     */
    protected function getRoleMenu($auth, $role, $sidebar){
        $roleMenu = [];
        $roleAction = [];
        foreach($auth as $controller=>$roleList){
            if(isset($roleList['role']) && is_array($roleList['role'])){
                if(!in_array($role, $roleList['role'])){
                    $roleMenu[$controller] = 0;
                }
                continue;
            }
            $bool = false;
            if(isset($roleList['action']) && is_array($roleList['action'])){
                foreach($roleList['action'] as $action=>$list){
                    if(isset($list['role']) && is_array($list['role'])){
                        if(!in_array($role, $list['role'])){
                            if(!isset($roleAction[$controller])){
                                $roleAction[$controller] = [];
                            }
                            $roleAction[$controller][$action] = 0;
                        }else{
                            $bool |= true;
                        }
                    }
                }
            }
            if(!$bool){
                $roleMenu[$controller] = 0;
            }
        }
        foreach($sidebar as $key=>$menu){
            if(isset($roleMenu[$key]) && $roleMenu[$key]==0){
                unset($sidebar[$key]);
                continue;
            }
            if(isset($roleAction[$key]) && is_array($roleAction[$key])){
                foreach($roleAction[$key] as $forbidden=>$val){
                    if($val==0){
                        unset($sidebar[$key]['list'][$forbidden]);
                    }
                }
            }
        }
        return $sidebar;
    }
    /**
     * 检查页面权限
     * @author carl.zhou
     * @param $pageInfo config文件定义的页面信息
     * @param $controller 当前请求的控制器
     * @param $action 当前请求的操作
     * @param $role 用户的权限角色
     * @return bool true 有权限 false 无权限
     */
    private function checkRole($pageInfo, $controller, $action, $role){
        $roleAuth = true;
        if (!isset($pageInfo[$controller])) {
            return $roleAuth;
        }
        $controllerInfo = $pageInfo[$controller];
        //控制器级别权限
        if (!empty($controllerInfo['role']) && is_array($controllerInfo['role'])) {
            if (!in_array($role, $controllerInfo['role'])) {
                $roleAuth = false;
            }
        }

        if (!isset($controllerInfo['action'][$action])) {
            return $roleAuth;
        }
        $actionInfo = $controllerInfo['action'][$action];
        //方法级别权限
        if (!empty($actionInfo['role']) && is_array($actionInfo['role'])) {
            if (!in_array($role, $actionInfo['role'])) {
                $roleAuth = false;
            }
        }
        return $roleAuth;
    }

    /**
     * 获取页面的title
     * @author carl.zhou
     * @param $pageInfo config文件定义的页面信息
     * @param $controller 当前请求的控制器
     * @param $action 当前请求的操作
     * @return string $title
     */
    protected function getPageTitle($pageInfo, $controller, $action){
        $title = '';
        if (isset($pageInfo[$controller])) {
            $controllerInfo = $pageInfo[$controller];
            if (isset($controllerInfo['action'][$action])) {
                $actionInfo = $controllerInfo['action'][$action];
                $title = empty($actionInfo['title']) ? '' :  $actionInfo['title'];
            }
        }
        return $title;
    }

    /**
     * 检查请求方式
     * @author carl.zhou
     * @return mixed
     */
    protected function checkRequestMethod(){
        $action = $this->request->action();
        $this->method = 'get';
        $this->isAjax = false;
        //判断是不是post
        if (substr($action, 0, 1) === '_') {
            $this->method = 'post';
            if (!$this->request->isPost()) {
                return $this->error('非法操作');
            }
            $action = substr($action, 1);

            if(strpos($action, 'action')){
//                $this->addAdminLog();
            }
        }
        //判断是不是ajax
        $temp = explode('_', $action);
        if (strtolower($temp[0]) === 'ajax') {
            $this->isAjax = true;
        }
    }




    /**
     * 根据登陆状态跳转
     */
    protected function checkLoginStatus(){
        //获取用户信息config
        $this->_userCfg = config('login_user');

        //检查是否登录
        $login = $this->isLogin();

        $module = $this->request->module();
        $controller = $this->request->controller();
        $action = $this->request->action();
        $url = $module."/".$controller."/".$action;
        if (!$login) {
            if($url == 'index/Index/index'){
                return $this->redirect('Login/index');
            }else{
                $this->error('您还未登录或是您的登录信息已过期', '/index/login' );
            }
        }
    }

    /**
     * 判断是否登录
     * @author Rocky Huang 2017-06-28
     * @return  boolean    [description]
     */
    private function isLogin()
    {
        if (!session($this->_userCfg['name'] )) {

            if($_SERVER['REQUEST_URI']){
                redirect($_SERVER['REQUEST_URI'])->remember();
            }
            return false;
        }
        return true;
    }

    public function ajaxSuccess($msg='成功', array $data=[]){
        if(!empty($data)){
            $data['message'] = $msg;
            return $this->json($data);
        }
        return $this->json(['status'=>0,'message'=>$msg]);
    }

    public function ajaxError($msg='失败'){
        return $this->json(['status'=>-1,'message'=>$msg]);
    }

    public function showError($msg, $url=''){
        if($this->isAjax){
            $data = ['message' => $msg,];
            $this->json($data);
        }
    }
}